package com.qd.admin.controller;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.core.weixinmanager.model.MiddleUser;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.MobileUtil;
import com.qd.common.sys.domain.entity.login.AppLoginUserDTO;
import com.qd.common.sys.domain.entity.login.AppWxLoginUserDTO;
import com.qd.common.sys.domain.login.AppUserExtend;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.core.service.app.AppLoginService;
import com.qd.core.service.app.AppWxLoginService;
import com.qd.system.util.FileConfirmUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * APP_登录
 *
 * @author sjk
 */
@RestController
@RequestMapping("/app/login")
@RequiredArgsConstructor
@Validated
@Slf4j
public class AppLoginController {
    private final AppLoginService appLoginService;
    private final AppWxLoginService appWxLoginService;

    /**
     * 用户端小程序注册
     *
     * @return token
     */
    @PostMapping(value = "/register")
    public ApiResultWrapper<Object> register(@Valid @RequestBody AppLoginUserDTO appLoginUser) {
        final String token = appLoginService.register(appLoginUser);
        return ApiResult.success(token);
    }

    /**
     * 基于unionId登录
     *
     * @return token
     */
    @PostMapping(value = "/loginByUnionId")
    public ApiResultWrapper<Object> loginByUnionId(@Valid @RequestBody Map<String, String> map) {
        String rId = map.get("rId");
        String unionId = map.get("unionId");
        if (!StringUtils.hasLength(rId)) {
            return ApiResult.error("rId不能为空");
        }
        if (!StringUtils.hasLength(unionId)) {
            return ApiResult.error("unionId不能为空");
        }
        final MiddleUser middleUser = new MiddleUser().setRId(rId).setUnionId(unionId);
        return ApiResult.success(appLoginService.login(middleUser));
    }

    /**
     * 门岗端小程序登录
     *
     * @return token
     */
    @PostMapping(value = "/loginByAccount")
    public ApiResultWrapper<Object> loginByAccount(@Validated @RequestBody Map<String, String> map) {
        String mobile = map.get("mobile");
        if (!StringUtils.hasLength(mobile)) {
            return ApiResult.error("手机号不能为空");
        }
        final String token = appLoginService.loginByAccount(mobile);
        return ApiResult.success(token);
    }

    /**
     * 小程序初始化
     *
     * @return token
     */
    @GetMapping(value = "/init")
    public ApiResultWrapper<Object> init(@Validated @NotBlank(message = "code不能为空") String code, @NotBlank(message = "appId不能为空") String appId, String promotionCode) {
        if (log.isDebugEnabled()) {
            log.debug("init");
        }
        final String token = appLoginService.isLogin(code, appId, promotionCode);
        return ApiResult.success(token);
    }

    /**
     * 获得用户信息
     *
     * @return token
     */
    @GetMapping(value = "/getUserInfo")
    public ApiResultWrapper<Object> getUserInfo() {
        Map<String, String> map = new HashMap<>(8);
        final String userId = SecurityUtils.getLoginUser().getUserId();
        String name = SecurityUtils.getLoginUser().getUser().getPersonName();
        String avatar = SecurityUtils.getLoginUser().getUser().getAvatarDisplay();
        String mobile = SecurityUtils.getLoginUser().getUser().getMobile();
        final AppUserExtend appUserExtend = SecurityUtils.getLoginUser().getUser().getAppUserExtend();
        if (null != appUserExtend) {
            name = appUserExtend.getNickName();
            avatar = appUserExtend.getAvatar();
            if (!StringUtils.hasLength(mobile)) {
                mobile = appUserExtend.getMobile();
            }
            final String promotionCode = appUserExtend.getPromotionCode();
            if (log.isDebugEnabled()) {
                log.debug("getUserInfo,promotionCode: {}", promotionCode);
            }
        }
        if (StringUtils.hasLength(avatar) && !avatar.startsWith(ConstantDto.HTTPS)) {
            avatar = FileConfirmUtil.getImageFile(avatar);
        }
        map.put("userId", userId);
        map.put("name", name);
        map.put("avatar", avatar);
        map.put("mobile", MobileUtil.getMobile(mobile));
        return ApiResult.success(map);
    }

    /**
     * 解除绑定
     *
     * @return 成功 or 失败
     */
    @PostMapping(value = "/unBind")
    public ApiResultWrapper<Object> unBind(@Validated @RequestBody Map<String, String> map) {
        String appId = map.get("appId");
        String userId = map.get("userId");
        if (!StringUtils.hasLength(appId)) {
            return ApiResult.error("小程序ID不能为空");
        }
        return appLoginService.unBind(appId, userId);
    }

    /**
     * 更新用户信息
     *
     * @return token
     */
    @PutMapping(value = "/updateLoginUser")
    public ApiResultWrapper<Object> updateLoginUser(@Valid @RequestBody Map<String, String> params) {
        String userId = SecurityUtils.getLoginUser().getUserId();
        String nickName = params.get("nickName");
        String headImg = params.get("avatar");
        if (!StringUtils.hasLength(nickName) && !StringUtils.hasLength(headImg)) {
            return ApiResult.error("昵称和头像不能都为空");
        }
        if (StringUtils.hasLength(headImg)) {
            if (headImg.startsWith(ConstantDto.HTTP) || headImg.startsWith(ConstantDto.HTTPS)) {
                return ApiResult.error("头像请设置为空");
            }
        }
        appLoginService.updateLoginUser(userId, nickName, headImg);
        return ApiResult.success();
    }

    /**
     * 跳转到公众号首页
     *
     * @param code     微信跳转的参数，用于获得openid
     * @param id       /wxmanager/wxApi/redirectAuthorizeUrl
     * @param state    微信跳转的参数
     * @param response 返回
     */
    @GetMapping(value = "/redirectIndex")
    public void redirectIndex(@Validated @NotBlank(message = "code不能为空") String code,
                              @NotBlank(message = "id不能为空") String id,
                              @NotBlank(message = "state不能为空") String state, HttpServletResponse response) {

        String redirect = appWxLoginService.buildRedirectUrl(code, state, id);
        try {
            if (log.isDebugEnabled()) {
                log.debug("跳转地址: {}", redirect);
            }
            response.sendRedirect(redirect);
        } catch (IOException e) {
            log.error("跳转首页异常", e);
            throw new ApiException(e);
        }
    }

    /**
     * 公众号用户注册
     *
     * @param appWxLoginUserDTO 注册信息
     * @return token
     */
    @PostMapping(value = "/wxRegister")
    public ApiResultWrapper<Object> wxRegister(@Valid @RequestBody AppWxLoginUserDTO appWxLoginUserDTO) {
        return ApiResult.success(appWxLoginService.register(appWxLoginUserDTO));
    }

}